package prototype.deepclone;

import java.io.*;

/**
 * @author shenhan
 * @create 2020/3/20 11:25
 * @description
 */
public class DeepProtoType implements Serializable, Cloneable {
    public String name;
    public DeepCloneableTarget deepCloneableTarget;

    public DeepProtoType() {
    }

    //深拷贝-方式一  -- clone方法

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        //基本数据类型和字符串的克隆
        deep = super.clone();
        //对引用数据类型单独处理
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();
//        ((DeepProtoType) deep).deepCloneableTarget = deepProtoType.deepCloneableTarget;
        return deep;
    }

    //深拷贝-方式二  --序列化（推荐）
    public Object deepClone() throws IOException {
        //创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);

            return ois.readObject();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }finally {
            bos.close();
            oos.close();
            bis.close();
            ois.close();
        }
        return null;
    }
}
